<template>
<!-- 新增用户弹框页 -->
  <el-dialog class="active_dialog"
  :visible.sync="visible" 
  title="新增用户" 
  @close="cancel"
  :close-on-click-modal="false" 
  :close-on-press-escape="false"
  :append-to-body="true"
  >
      <!-- <header class="top">
        <span>添加用户</span>
        <div>
          <span @click="dialogConfirm('cancel')" class="exit">X</span>
        </div>
      </header> -->
      <div class="adduser">
        <!-- 用户录入 -->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="用户录入" name="first">
            <!-- 添加入党积极分子 -->
            <el-form class="adduser_form" label-position="roght" label-width="85px" :model="saveUserDto">
              <el-form-item label="入党阶段">
                <!-- 下拉选择框 -->
                <el-select v-model="saveUserDto.politics" clearable placeholder="入党阶段">
                  <el-option
                    v-for="item in stage"
                    :key="item.id"
                    :value="item.name">
                  </el-option>
                </el-select>
                <!-- <el-input v-model="saveUserDto.politics" clearable placeholder="团员推优/入党积极分子/发展对象/预备党员/党员"></el-input> -->
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="saveUserDto.name" clearable></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-input v-model="saveUserDto.gender" clearable></el-input>
              </el-form-item>
              <el-form-item label="用户名">
                <el-input v-model="saveUserDto.username" clearable></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="saveUserDto.password" clearable></el-input>
              </el-form-item>
              <el-form-item label="出生日期">
                <!-- <el-input v-model="saveUserDto.academyName"></el-input> -->
                <div class="block">
                  <el-date-picker
                    value-format="yyyy-MM-dd HH:mm:ss"
                    v-model="saveUserDto.birth"
                    type="datetime"
                    placeholder="选择日期">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="户籍地址">
                <el-input v-model="saveUserDto.censusAddress" clearable></el-input>
              </el-form-item>
              <el-form-item label="学院名称">
                <!-- <el-input v-model="saveUserDto.academyName"></el-input> -->
                <el-select v-model="saveUserDto.academyName" clearable placeholder="选择学院">
                  <el-option
                    v-for="item in academyList"
                    :key="item.id"
                    :value="item.academyName">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="专业名称">
                <!-- <el-input v-model="saveUserDto.majorName"></el-input> -->
                <el-select v-model="saveUserDto.majorName" clearable placeholder="选择专业">
                  <el-option
                    v-for="item in majorList"
                    :key="item.id"
                    :value="item.majorName">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="班级名称">
                <!-- <el-input v-model="saveUserDto.className"></el-input> -->
                <el-select v-model="saveUserDto.className" clearable placeholder="选择班级">
                  <el-option
                    v-for="item in classList"
                    :key="item.id"
                    :value="item.className">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="入团时间">
                <!-- <el-input v-model="saveUserDto.entryTime"></el-input> -->
                <div class="block">
                  <el-date-picker
                    v-model="saveUserDto.entryTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="身份证">
                <el-input v-model="saveUserDto.identity" clearable></el-input>
              </el-form-item>
              <el-form-item label="民族">
                <el-input v-model="saveUserDto.nationality" clearable></el-input>
              </el-form-item>
              <el-form-item label="党组织名称">
                <!-- <el-input v-model="saveUserDto.partyOrganizationName"></el-input> -->
                <el-select v-model="saveUserDto.partyOrganizationName" clearable placeholder="选择党组织">
                  <el-option
                    v-for="item in organizationList"
                    :key="item.id"
                    :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="党龄">
                <el-input v-model="saveUserDto.partyStanding" clearable></el-input>
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="saveUserDto.phoneNumber" clearable></el-input>
              </el-form-item>
              <el-form-item label="身份">
                <el-input v-model="saveUserDto.position" clearable></el-input>
              </el-form-item>
              <el-form-item label="居住地址">
                <el-input v-model="saveUserDto.residentialAddress" clearable></el-input>
              </el-form-item>
              <el-form-item label="用户权限">
                <!-- <el-input v-model="saveUserDto.roleName" clearable placeholder="学校党委/学院党委/支部/普通用户"></el-input> -->
                <el-select v-model="saveUserDto.roleName" clearable placeholder="用户权限">
                  <el-option
                    v-for="item in quanxian"
                    :key="item.id"
                    :value="item.roleName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="批量导入" name="second">
            <div>
              <el-button type="primary" @click="download">点击下载模板</el-button>
            </div>
            <div class="importdata">
              <!-- <input type="file" accept=".xls,.xlsx" @change="importData"> -->
              <el-upload 
              class="upload"
              ref="piliang"
              action="#" 
              :show-file-list="false"
              :on-change="handleExcel"
              accept="'.xlsx','.xls'"
              :auto-upload="false"
              :headers="headers">
                <!-- <input type="file" accept=".xls,.xlsx" @change="importData"> -->
                <el-button>导入文件</el-button>
                <span v-if="addFile !=[]">{{addFile.name}}</span>
                <!-- <input type="file" @change="onChange" class="file-ipt" /> -->
              </el-upload>
            </div>
          </el-tab-pane>
        </el-tabs>
          <div class="sure_button">
            <el-button @click="ConfirmAdd(activeName)" class="affirm" type="primary">确认添加</el-button>
            <el-button @click="dialogConfirm('cancel')">取消</el-button>
          </div>
      </div>
  </el-dialog>
</template>

<script>
// import axios from "axios"
import { read, utils } from "xlsx"; // 注意处理方法引入方式
export default {
    name:"addFrame",
    props:{
      personInfo:{}
    },
    data(){
      return{
        visible: false,
        saveUserDto: {
          // organization:"",
          name: '',//姓名
          gender: '',//性别
          username: '',//用户名
          password:"",//密码
          politics:"",//政治面貌
          academyName:"",//学院名称
          birth:"",//出生日期
          censusAddress:"",//户籍地址
          className:"",//班级名称
          identity:"",//身份证
          majorName:"",//专业名称
          nationality:"",//民族
          partyOrganizationName:"",//党组织名称
          partyStanding:"",//党龄
          entryTime:"",//入团时间
          phoneNumber:"",//手机号
          position:"",//职位
          residentialAddress:"",//居住地址
          roleName:"",//用户权限
        },
        options:[],
        showsingle:true,
        tabData:[],
        activeName: 'first',
        majorList:[],//专业列表
        academyList:[],//学院列表
        classList:[],//班级列表
        organizationList:[],//党组织列表
        // key:0,
        headers: {"Content-Type": "multipart/form-data;charset=UTF-8"},
        addFile:"",//上传的文件
        tableData:[],
        tableHead:[],
        fileList:[],//上传文件列表
        headSculpture:"",//修改后的头像
        quanxian:[],//用户权限列表
        stage:[
          {
            id:"0",
            name:"团员"
          },{
            id:"1",
            name:"入党积极分子"
          },{
            id:"2",
            name:"发展对象"
          },{
            id:"3",
            name:"预备党员"
          },{
            id:"4",
            name:"党员"
          },
        ]
      }
    },
    mounted(){
      // console.log(this.personInfo)
      this.options = this.personInfo//接收父组件传过来的党组织列表
      // console.log(this.options)

    },
    methods:{
      init () {
        this.visible = true
        this.$nextTick(() => {
          // this.$refs['dataForm'].resetFields()
        })
        // 查询专业列表
        this.axios({
          headers:{ 'Authentication':localStorage.getItem('token')},
          method:"get",
          // url:"api/major/getMajorList",
          url:"/major/getMajorList",
        }).then(res=>{
          if(res.data.code != 20001){
            return this.$message.error(res.data.msg)
          }
          this.majorList = res.data.data
        })
        // 查询学院列表/academy/getAcademyList
        this.axios({
          headers:{ 'Authentication':localStorage.getItem('token')},
          method:"get",
          // url:"api/academy/getAcademyList",
          url:"/academy/getAcademyList",
        }).then(res=>{
          if(res.data.code != 20001){
            return this.$message.error(res.data.msg)
          }
          this.academyList = res.data.data
        })
        // 查询班级列表/class/getClassList
        this.axios({
          headers:{ 'Authentication':localStorage.getItem('token')},
          method:"get",
          // url:"api/class/getClassList",
          url:"/class/getClassList",
        }).then(res=>{
          if(res.data.code != 20001){
            return this.$message.error(res.data.msg)
          }
          this.classList = res.data.data
        })
        // 查询党组织列表
        this.axios({
          headers:{ 'Authentication':localStorage.getItem('token')},
          method:"get",
          // url:"api/organization/getOrganizationList",
          url:"/organization/getOrganizationList",
        }).then(res=>{
          if(res.data.code != 20001){
            return this.$message.error(res.data.msg)
          }
          this.organizationList = res.data.data
        })
        this.axios({//查询权限列表
          headers:{ 'Authentication':localStorage.getItem('token')},
          method:"get",
          // url:"api/role/getRoleList",
          url:"/role/getRoleList",
        }).then(res=>{
          if(res.data.code != 20001){
            return this.$message.error(res.data.msg)
          }
          this.quanxian = res.data.data
        })
      },
      cancel(){//点击取消按钮
        this.visible = false
        this.saveUserDto = {}//清空输入框中之前输入的内容
        this.$refs.piliang.clearFiles()//清空选择的excel表
      },
      dialogConfirm(res){//关闭弹窗按钮
        this.$emit('toclose', false);
        this.showmodify = false
        cosole.log(this.$refs.piliang)
        // this.$refs.piliang.clearFiles()//清空选择的excel表
      },
      handleClick(tab, event){//tabs头部切换按钮
        // console.log(tab,event)
        // console.log(this.activeName)
      },
      ConfirmAdd(e){//确认添加按钮
        // console.log(this.saveUserDto)
        // console.log(e)
        var _this = this
        if(e=="first"){//录入单个
          // console.log("执行")
          if(this.saveUserDto.politics==""||this.saveUserDto.name==""||this.saveUserDto.gender==""||this.saveUserDto.username==""||this.saveUserDto.password==""){
            return this.$message.error("必填项不能为空！")
          }
          this.axios({
            headers:{ 'Authentication':localStorage.getItem('token')},
            method:"post",
            // url:"api/user/save",
            url:"/user/save",
            data:this.saveUserDto
          }).then(res=>{
            // console.log(res)
            if(res.data.code != 20001){
              return this.$message.error(res.data.msg)
            }
            this.$alert('添加成功', {
              confirmButtonText: '确定',
              callback: action => {
                this.visible = false
                this.saveUserDto = {}//清空输入框中之前输入的内容
                this.$emit('userList')
              }
            });
          })
        } else if(e=="second"){//批量导入
          // console.log("批量导入")
          let formData = new FormData(); //声明一个formData对象
          formData.append("userList", this.addFile.raw);    //把文件信息放入对象中
          // var userList = formData
          this.axios({
            headers:{ 'Authentication':localStorage.getItem('token')},
            method:"post",
            // url:"api/user/saveList",
            url:"/user/saveList",
            data:formData
          }).then(res=>{
            // console.log(res)
            if(res.data.code != 20001){
              return this.$message.error(res.data.msg)
            }
            this.$alert('批量导入成功', {
              confirmButtonText: '确定',
              callback: action => {
                this.visible = false
                // 调用父组件的userList方法刷新列表数据
                this.$emit('userList')
              }
            });
          })
        }
      },
      handleExcel(file){//导入表格
        // console.log(file)
        this.addFile = file
        const files = { 0: file };
        this.readExcel(files)
      },
      readExcel(file) {//提取表格中的内容
        const fileReader = new FileReader();
        fileReader.onload = ev => {
          try {
            // console.log(ev)
            const data = ev.target.result;
            const workbook = read(data, { type: "binary" });
            const params = [];
            // 取对应表生成json表格内容
            workbook.SheetNames.forEach(item => {
              this.tableData.push(utils.sheet_to_json(workbook.Sheets[item]));
            });
            // 该算法仅针对表头无合并的情况
            if (this.tableData.length > 0) {
              // 获取excel中第一个表格数据tableData[0][0]，并且将表头提取出来
              for (const key in this.tableData[0][0]) {
                this.tableHead.push(key);
              }
            }
            // 重写数据
          } catch (e) {
            // console.log("error:" + e);
            return false;
          }
        };
        fileReader.readAsBinaryString(file[0].raw);
      },
      download(){//点击下载模板
        this.axios({
          headers:{ 'Authentication':localStorage.getItem('token')},
          method:"get",
          // url:"api/user/getTemplate",
          url:"/user/getTemplate",
        }).then(res=>{
          // console.log(res.data.data)
          if(res.data.code != 20001){
            return this.$message.error(res.data.msg)
          }
          window.location.href = res.data.data
        })
      }
    }
}
</script>

<style lang="scss">
.active_dialog{
  // height: 53vh;
  .el-tab-pane{
    height: 52vh;
    
    overflow: auto;
  }
  .el-dialog__body{
    padding: 0 20px;
  }
}
    .top{//头部
      display: flex;
      border-bottom: #1e1f3b 1px solid;
      padding-bottom: 1.5vh;
      margin: 0 0.5vw;
      span{
        flex: 1;
        color: #9bd6ff;
      }
      .exit{
        cursor: pointer;
        text-align: right;
      }
    }
    .adduser{//用户录入及用户导入部分
      // margin-top: 2vh;
      // position: relative;
      height: 80%;
      overflow: auto;
      .adduser_form{
        // margin-top: 5vh;
        width: 90%;
      }
      .batch{
        position: absolute;
        // bottom: 15vh;
        right: 7vw;
      }
      .importdata{
        border: 1px solid #000;
        width: 70%;
        margin: 3vh auto;
        text-align: center;
        height: 40vh;
        line-height: 40vh;
      }
      .affirm{//确认添加单个用户按钮
      }
    }
    .sure_button{
      text-align: center;
      // border: 1px solid #ccc;
      margin: 2vh;
      padding-bottom: 2vh;
    }
</style>